<template>
  <div class="trigger-rule-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>触发规则管理</span>
          <el-button type="primary" @click="showAddRuleDialog">新增规则</el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选 -->
      <div class="search-filter">
        <el-input v-model="searchQuery" placeholder="搜索规则名称" prefix-icon="Search" style="width: 300px; margin-right: 15px;"></el-input>
        <el-select v-model="selectedTemplate" placeholder="选择提醒模板" style="width: 200px; margin-right: 15px;">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="template in templates" :key="template.id" :label="template.name" :value="template.id"></el-option>
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      
      <!-- 规则表格 -->
      <el-table :data="rulesData" style="width: 100%">
        <el-table-column prop="id" label="规则ID" width="80"></el-table-column>
        <el-table-column prop="name" label="规则名称" min-width="200"></el-table-column>
        <el-table-column prop="templateName" label="提醒模板" width="180"></el-table-column>
        <el-table-column prop="triggerType" label="触发类型" width="120">
          <template #default="scope">
            <el-tag :type="getTriggerTypeTag(scope.row.triggerType)">
              {{ getTriggerTypeName(scope.row.triggerType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="triggerCondition" label="触发条件" min-width="250">
          <template #default="scope">
            <div class="condition-preview" :title="scope.row.triggerCondition">
              {{ scope.row.triggerCondition }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch v-model="scope.row.status" @change="handleToggleStatus(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="primary" size="small" @click="showEditRuleDialog(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 新增/编辑规则对话框 -->
    <el-dialog v-model="ruleDialogVisible" :title="dialogTitle" width="700px">
      <el-form :model="ruleForm" :rules="ruleRules" ref="ruleFormRef" label-width="120px">
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入规则名称"></el-input>
        </el-form-item>
        <el-form-item label="提醒模板" prop="templateId">
          <el-select v-model="ruleForm.templateId" placeholder="请选择提醒模板">
            <el-option v-for="template in templates" :key="template.id" :label="template.name" :value="template.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="触发类型" prop="triggerType">
          <el-select v-model="ruleForm.triggerType" placeholder="请选择触发类型">
            <el-option label="定时触发" value="time"></el-option>
            <el-option label="条件触发" value="condition"></el-option>
            <el-option label="手动触发" value="manual"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="ruleForm.triggerType === 'time'" label="触发时间" prop="triggerTime">
          <el-time-picker v-model="ruleForm.triggerTime" placeholder="选择时间" value-format="HH:mm"></el-time-picker>
        </el-form-item>
        <el-form-item v-if="ruleForm.triggerType === 'condition'" label="触发条件" prop="triggerCondition">
          <el-input v-model="ruleForm.triggerCondition" type="textarea" :rows="3" placeholder="请输入触发条件表达式"></el-input>
          <div class="form-tip">例如：user.score < 60 || user.loginDays >= 7</div>
        </el-form-item>
        <el-form-item label="规则说明" prop="description">
          <el-input v-model="ruleForm.description" type="textarea" :rows="2" placeholder="请输入规则说明"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="ruleForm.status"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="ruleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveRule">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 搜索和筛选条件
const searchQuery = ref('')
const selectedTemplate = ref('')

// 表格数据
const rulesData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 提醒模板数据
const templates = ref([
  { id: 1, name: '每日健康提醒' },
  { id: 2, name: '锻炼完成提醒' },
  { id: 3, name: '治疗进度提醒' }
])

// 对话框状态
const ruleDialogVisible = ref(false)
const editingRuleId = ref(null)
const ruleFormRef = ref()

// 规则表单
const ruleForm = reactive({
  name: '',
  templateId: '',
  triggerType: 'time',
  triggerTime: '',
  triggerCondition: '',
  description: '',
  status: true
})

// 表单验证规则
const ruleRules = {
  name: [
    { required: true, message: '请输入规则名称', trigger: 'blur' },
    { min: 3, max: 100, message: '规则名称长度在 3 到 100 个字符', trigger: 'blur' }
  ],
  templateId: [
    { required: true, message: '请选择提醒模板', trigger: 'change' }
  ],
  triggerType: [
    { required: true, message: '请选择触发类型', trigger: 'change' }
  ],
  triggerTime: [
    { required: () => ruleForm.triggerType === 'time', message: '请选择触发时间', trigger: 'change' }
  ],
  triggerCondition: [
    { required: () => ruleForm.triggerType === 'condition', message: '请输入触发条件', trigger: 'blur' },
    { min: 10, message: '触发条件至少10个字符', trigger: 'blur' }
  ],
  description: [
    { min: 5, max: 200, message: '规则说明长度在 5 到 200 个字符', trigger: 'blur' }
  ]
}

// 对话框标题
const dialogTitle = computed(() => {
  return editingRuleId.value ? '编辑规则' : '新增规则'
})

// 获取触发类型标签样式
const getTriggerTypeTag = (triggerType) => {
  const typeMap = {
    'time': 'success',
    'condition': 'warning',
    'manual': 'info'
  }
  return typeMap[triggerType] || 'primary'
}

// 获取触发类型名称
const getTriggerTypeName = (triggerType) => {
  const nameMap = {
    'time': '定时触发',
    'condition': '条件触发',
    'manual': '手动触发'
  }
  return nameMap[triggerType] || triggerType
}

// 获取模板名称
const getTemplateName = (templateId) => {
  const template = templates.value.find(t => t.id === templateId)
  return template ? template.name : '未知模板'
}

// 获取规则列表
const fetchRules = () => {
  // 实际项目中应该从后端获取数据
  // 这里使用模拟数据
  const mockData = [
    {
      id: 1,
      name: '每日健康提醒规则',
      templateId: 1,
      templateName: '每日健康提醒',
      triggerType: 'time',
      triggerTime: '09:00',
      triggerCondition: '',
      status: true,
      createdAt: '2023-07-01 10:00:00'
    },
    {
      id: 2,
      name: '连续锻炼奖励规则',
      templateId: 2,
      templateName: '锻炼完成提醒',
      triggerType: 'condition',
      triggerTime: '',
      triggerCondition: 'user.consecutiveExerciseDays >= 7',
      status: true,
      createdAt: '2023-07-02 11:00:00'
    },
    {
      id: 3,
      name: '治疗进度跟踪规则',
      templateId: 3,
      templateName: '治疗进度提醒',
      triggerType: 'time',
      triggerTime: '18:00',
      triggerCondition: '',
      status: false,
      createdAt: '2023-07-03 12:00:00'
    }
  ]
  
  // 应用搜索和筛选
  let filteredData = [...mockData]
  if (searchQuery.value) {
    filteredData = filteredData.filter(rule => 
      rule.name.includes(searchQuery.value)
    )
  }
  if (selectedTemplate.value) {
    filteredData = filteredData.filter(rule => rule.templateId === Number(selectedTemplate.value))
  }
  
  total.value = filteredData.length
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  rulesData.value = filteredData.slice(start, end)
}

// 显示新增规则对话框
const showAddRuleDialog = () => {
  editingRuleId.value = null
  // 重置表单
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields()
  }
  // 重置表单数据
  ruleForm.name = ''
  ruleForm.templateId = ''
  ruleForm.triggerType = 'time'
  ruleForm.triggerTime = ''
  ruleForm.triggerCondition = ''
  ruleForm.description = ''
  ruleForm.status = true
  ruleDialogVisible.value = true
}

// 显示编辑规则对话框
const showEditRuleDialog = (rule) => {
  editingRuleId.value = rule.id
  ruleForm.id = rule.id
  ruleForm.name = rule.name
  ruleForm.templateId = rule.templateId
  ruleForm.triggerType = rule.triggerType
  ruleForm.triggerTime = rule.triggerTime
  ruleForm.triggerCondition = rule.triggerCondition
  ruleForm.description = rule.description || ''
  ruleForm.status = rule.status
  ruleDialogVisible.value = true
}

// 保存规则
const handleSaveRule = () => {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      // 实际项目中应该调用API保存数据
      ElMessage.success(editingRuleId.value ? '规则编辑成功' : '规则新增成功')
      ruleDialogVisible.value = false
      fetchRules()
    }
  })
}

// 切换规则状态
const handleToggleStatus = (rule) => {
  // 实际项目中应该调用API更新状态
  ElMessage.success(`规则${rule.status ? '已启用' : '已禁用'}`)
  fetchRules()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchRules()
}

// 重置搜索
const resetSearch = () => {
  searchQuery.value = ''
  selectedTemplate.value = ''
  currentPage.value = 1
  fetchRules()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchRules()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  fetchRules()
}

// 初始化数据
fetchRules()
</script>

<style scoped>
.trigger-rule-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-filter {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.form-tip {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}

.condition-preview {
  word-break: break-all;
  color: #303133;
}
</style>